package com.icebergteam.warfacewidget.videos.ui;

import java.util.ArrayList;
import java.util.Locale;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.text.Html;
import android.view.View;
import android.widget.RemoteViews;
import com.icebergteam.warfacewidget.AppManager;
import com.icebergteam.warfacewidget.R;
import com.icebergteam.warfacewidget.core.IntentService;
import com.icebergteam.warfacewidget.core.ListViewFactory;
import com.icebergteam.warfacewidget.core.LogManager;
import com.icebergteam.warfacewidget.core.NotificationMessage;
import com.icebergteam.warfacewidget.core.NotificationService;
import com.icebergteam.warfacewidget.core.Parser;
import com.icebergteam.warfacewidget.core.utils.TimeDateUtils;
import com.icebergteam.warfacewidget.core.utils.ViewUtils;
import com.icebergteam.warfacewidget.data.sql.VideosTable;
import com.icebergteam.warfacewidget.ui.YouTubeVideoPlayerActivity;
import com.icebergteam.warfacewidget.videos.data.VideosItem;

public class VideosListViewFactory extends ListViewFactory {
	public static String className = VideosListViewFactory.class
			.getCanonicalName();

	private ArrayList<VideosItem> listVideosItems = new ArrayList<VideosItem>();
	
	public VideosListViewFactory(Context ctxt, Intent intent) {
		super(ctxt, intent);
		try {
			listVideosItems = AppManager.getDatabase().getVideosTable().getVideosList();
			count = listVideosItems.size();
			
			int number = 0;
			String bigContentText = "";
			
			boolean checkRestore = intent.getExtras() != null && intent.getExtras().getBoolean(Parser.KEY_INTENT_RESTORE) == false;
			
			int firstUnreadedItemIndex = -1;
			for(int i=0; i < listVideosItems.size(); i++){
				VideosItem item = listVideosItems.get(i);
				if(checkRestore && !item.isRead()){
					number ++;
					bigContentText += item.getTitle() + "\n";
					if(firstUnreadedItemIndex < 0){
						firstUnreadedItemIndex = i;
					}
				}
			}
			
			if(checkRestore && !bigContentText.isEmpty()){
				
				VideosItem item = listVideosItems.get(firstUnreadedItemIndex);
				
				NotificationMessage message = new NotificationMessage();
				message.setNumber(number);
				message.setBigContentText((firstUnreadedItemIndex < firstUnreadedItemIndex + number -1 ) ? bigContentText: null);
				message.setSmallContentText(item.getTitle());
				message.setImage(ViewUtils.scaleImage(item.getImgSrc(), 150));
				message.setFirstUnreadedItemIndex(firstUnreadedItemIndex);
				message.setTitle(String.format("%s %s", AppManager.getContext().getResources().getString(R.string.project_name), AppManager.getContext().getResources().getString(R.string.youtube_video_player_title)));
				message.setTickerTitle(String.format("%s (%s)\n%s", message.getTitle(), number, message.getSmallContentText()));
				message.setSmallIcon(BitmapFactory.decodeResource(AppManager.getContext().getResources(),R.drawable.widget_service_videos_icon));
								
				Intent i = new Intent(AppManager.getContext(), YouTubeVideoPlayerActivity.class);
				i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
						| Intent.FLAG_ACTIVITY_CLEAR_TASK);
				i.putExtra(YouTubeVideoPlayerActivity.KEY_INTENT_ID, item.getVideoUrl());
				i.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1));
				i.putExtra(IntentService.KEY_INTENTSERVICE, IntentService.UPDATE_VIDEOS_READ);
				i.putExtra(VideosTable.FIELD_URL, item.getUrl());
				i.putExtra(VideosTable.FIELD_READ, true);
				
				PendingIntent pendingIntent = PendingIntent.getActivity(AppManager.getContext(), 0,
						i, PendingIntent.FLAG_UPDATE_CURRENT);
				
				message.setIntent(pendingIntent);
				
				Intent intentNotif = new Intent(intent);
				intentNotif.setClass(AppManager.getContext(), NotificationService.class);
				intentNotif.putExtra(NotificationService.KEY_NOTIF_MESSAGE, message);
					
				AppManager.getContext().startService(intentNotif);
			}
			
			LogManager.LogV(VideosListViewFactory.className,LogManager.getExecuteMethodName(),
							listVideosItems,
							((ctxt == null) ? ctxt == null : ctxt.toString()), count);
		
		} catch (Exception e) {
			LogManager.LogEA(className, e.getLocalizedMessage());
			e.printStackTrace();
		} 
	}

	@Override
	public RemoteViews getViewAt(int position) {
		try {
			VideosItem videosItem = listVideosItems.get(position);
			RemoteViews row = new RemoteViews(context.getPackageName(),
					R.layout.videos_list_item_widget_layout);
			if(videosItem != null){
				row.setTextViewText(R.id.videos_list_item_widget_layout_title_textview,
							Html.fromHtml(videosItem.getTitle()));
				row.setTextViewText(R.id.videos_list_item_widget_layout_pubdatee_textview,
						TimeDateUtils.getDateStringFromNormalTimestamp(videosItem.getPubdate(), "dd MMM yyyy HH:mm",  new Locale(AppManager.getLocaleManager().getCurrentUILangId())));
				row.setImageViewBitmap(R.id.videos_list_item_widget_layout_img_imageview,
								ViewUtils.scaleImage(videosItem.getImgSrc(), 100));
				row.setViewVisibility(R.id.videos_list_item_widget_layout_newicon, (videosItem.isRead())?  View.GONE: View.VISIBLE);
				
			
				
				/*create source for IntentService*/
				Intent i = new Intent();
				i.putExtra(YouTubeVideoPlayerActivity.KEY_INTENT_ID, videosItem.getVideoUrl());
				i.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1));
				i.putExtra(IntentService.KEY_INTENTSERVICE, IntentService.UPDATE_VIDEOS_READ);
				i.putExtra(VideosTable.FIELD_URL, videosItem.getUrl());
				i.putExtra(VideosTable.FIELD_READ, true);
				
				row.setOnClickFillInIntent(R.id.videos_list_item_widget_layout, i);
			}
			return row;
		} catch (NumberFormatException e) {
			LogManager.LogE(VideosListViewFactory.className, LogManager.getExecuteMethodName(), e.getLocalizedMessage());
			e.printStackTrace();
		} catch (Exception e) {
			LogManager.LogE(VideosListViewFactory.className, LogManager.getExecuteMethodName(), e.getLocalizedMessage());
			e.printStackTrace();
		}
		return null;
	}
}